<template>
  <div class="dropdown" ref="dropdownRef">
    <a
      href="#"
      class="btn btn-outline-light my-2 dropdown-toggle"
      @click.prevent="toggle"
    >
      {{ title }}
    </a>
    <div
      class="dropdown-menu"
      aria-labelledby="dropdownMenuButton"
      :style="{ display: 'block' }"
      v-if="isOpen"
    >
      <slot></slot>
    </div>
  </div>
</template>
<script lang='ts'>
import { defineComponent, ref, onMounted, onUnmounted, watch } from "vue";
import useClickOutside from "../hooks/useClickOutside";
export default defineComponent({
  name: "Dropdown",
  props: {
    title: {
      type: String,
      required: true,
    },
  },
  components: {},
  setup() {
    // 响应式！！！
    let isOpen = ref(false);
    const toggle = () => {
      isOpen.value = !isOpen.value;
    };
    // dropdownRef命名和上面ref=“dropdownRef”一致，挂载之后就可以拿到dom节点
    // 要设置联合类型
    const dropdownRef = ref<null | HTMLElement>(null);
    const isClickOutside = useClickOutside(dropdownRef);
    watch(isClickOutside, () => {
      if (isClickOutside.value && isOpen.value) {
        // 用ref请时刻记得.value
        isOpen.value = false;
      }
    });
    return {
      isOpen,
      dropdownRef,
      toggle,
    };
  },
});
</script>
<style scoped>
</style>